let global_page = 1,
  global_limit = 5,
  providerUrl = '/provider';

function loadProvider(name) {
  if (name === 'undefined') name = '';
  $.get(providerUrl + '/findAllByPage', {
    page: global_page,
    limit: global_limit,
    name: name
  }, providers => {
    if (providers.data.length === 0 && global_page > 1) {
      global_page--;
      loadProvider();
    } else {
      loadProviders(providers);
      loadProviderLayPage(providers);
    }
  });
}

function loadProviders(info) {
  layui.use(['table', 'layer'], () => {
    let table = layui.table,
      layer = layui.layer;
    table.render({
      elem: '#provider',
      data: info.data,
      limit: global_limit,
      toolbar: '#provider-toolbar',
      cols: [
        [
          {type: 'checkbox'},
          {field: 'id', title: '供应商ID'},
          {field: 'name', title: '供应商名称'},
          {field: 'contact', title: '联系人'},
          {field: 'phone', title: '联系电话'},
          {field: 'address', title: '联系地址'},
          {title: '操作', toolbar: '#provider-tool'}
        ]
      ]
    });
    table.on('toolbar(provider)', data => {
      let event = data.event;
      switch (event) {
        case 'add':
          $('#add-provider-layout input[name=operator]').val($('.layui-nav-item').children('a:eq(0)').text());
          showLayout($('#add-provider-layout'));
          break;
        case 'del':
          layer.confirm('是否删除选中的供应商信息?', {
            btn: ['确定删除', '再想想']
          }, () => {
            let providers = table.checkStatus(data.config.id).data,
              ids = [];
            $.each(providers, (i, v) => {
              ids.push(v.id);
            });
            ids = JSON.stringify(ids);
            $.post(providerUrl + '/delProvider/' + ids.substring(1, ids.length - 1), result => {
              result = result > 0 ? '成功' : '失败';
              layer.msg('供应商信息删除' + result + '!');
              loadProvider();
            });
          });
          break;
        case 'search':
          let name = $('#search').val();
          loadProvider(name);
          break;
      }
    });
    table.on('tool(provider)', data => {
      let event = data.event,
        field = data.data;
      switch (event) {
        case 'detail':
          $.get(providerUrl + '/findById/' + field.id, provider => {
            let input = $('#detail-provider-layout form').find('input');
            $.each(input, (i, v) => {
              input.eq(i).val(provider[input.eq(i).attr('name')]);
            });
            $('#detail-provider-layout .layout-title span').html(provider.name);
          });
          showLayout($('#detail-provider-layout'));
          break;
        case 'edit':
          $.get(providerUrl + '/findById/' + field.id, provider => {
            let input = $('#edit-provider-layout form').find('input');
            $.each(input, (i, v) => {
              input.eq(i).val(provider[input.eq(i).attr('name')]);
            });
            $('#edit-provider-layout .layout-title span').html(provider.name);
          });
          showLayout($('#edit-provider-layout'));
          break;
        case 'del':
          layer.confirm('是否删除此供应商信息?', {
            btn: ['确定', '再想想']
          }, () => {
            $.post(providerUrl + '/delProvider/' + field.id, result => {
              result = result > 0 ? '成功' : '失败';
              layer.msg('供应商信息删除' + result + '!');
              loadProvider();
            });
          });
          break;
      }
    });
  });
}

function loadProviderLayPage(info) {
  layui.use('laypage', () => {
    let laypage = layui.laypage;
    laypage.render({
      elem: 'provider-page',
      curr: global_page,
      limit: global_limit,
      limits: [5, 10, 20, 50],
      count: info.count,
      layout: ['count', 'prev', 'page', 'next', 'limit'],
      jump: function (obj, first) {
        if (!first) {
          global_page = obj.curr;
          global_limit = obj.limit;
          loadProvider();
        }
      }
    });
  })
}

function loadProviderAction() {
  layui.use(['element', 'form', 'layer'], () => {
    let form = layui.form,
      layer = layui.layer;
    form.on('submit(add)', data => {
      let field = data.field;
      $.get(providerUrl + '/findByName', {name: field.name}, provider => {
        if (provider !== '') {
          layer.msg('供应商已存在，请勿重复添加!');
        } else {
          if (!/1[2-9][0-9]{9}/ig.test(field.phone) && field.name.length !== 11) {
            layer.msg('联系电话格式有误，请输入11位手机号码!');
          } else {
            $.post(providerUrl + '/addProvider', field, result => {
              result = result > 0 ? '成功' : '失败';
              layer.msg('供应商添加' + result + '!');
              hideLayout($('#add-provider-layout'));
              loadProvider();
            });
          }
        }
      });
    });
    form.on('submit(edit)', data => {
      let field = data.field;
      if (!regexPhone(field.phone)) {
        layer.msg('手机号格式有误，请输入11位正确手机号!');
      } else {
        $.post(providerUrl + '/updateProvider', field, result => {
          result = result > 0 ? '成功' : '失败';
          layer.msg('供应商信息更新' + result + '!');
          hideLayout($('#edit-provider-layout'));
          loadProvider();
        });
      }
    });
  });
}

loadProviderAction();
